import {
  getToken, setToken, removeToken,
  getRefreshToken, setRefreshToken,
  getTenantCode, setTenantCode
} from '@/utils/auth'
import { login, logout, getInfo, getCaptcha } from '@/api/user'
import { updatePassword } from '@/api/menber'
import { resetRouter } from '@/router'
import md5 from 'blueimp-md5'

let timer = 1000 * 60 * 60
let timeFn = null

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    userInfo: {},
    roles: [],
    refreshToken: getRefreshToken(),
    tenantCode: getTenantCode(),
    captcha: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, { ...getDefaultState() })
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_REFRESHTOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
    setRefreshToken(refreshToken)
  },
  SAVE_TENANT_CODE: (state, tenantCode) => {
    if (tenantCode) {
      setTenantCode(tenantCode)
      state.tenantCode = tenantCode
    }
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  },
  SET_CAPTCHA: (state, captcha = {}) => {
    state.captcha = captcha
  }
}

const actions = {
  // user login
  login({ dispatch, commit, state }, userInfo) {
    const { username, password, tenantCode, code } = userInfo
    return new Promise((resolve, reject) => {
      // 登录类型
      const grantType = 'password'
      let encodePW = md5(password)
      encodePW = encodePW.toLocaleUpperCase()
      login({ loginId: username.trim(), passWord: encodePW, grantType, tenantCode, key: state.captcha.key, code })
        .then(response => {
          const { data: { user, ...tokens } = {}} = response
          commit('SAVE_TENANT_CODE', tenantCode)
          dispatch('saveToken', tokens)
          dispatch('saveInfo', user)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },

  resetPassword({ commit }, param) {
    const { oldPw, newPw } = param
    const E_npw = md5(newPw)
    const encodePW = md5(oldPw)// 'e10adc3949ba59abbe56e057f20f883e'
    // console.log(param, { newPw: E_npw, oldPw: encodePW })
    updatePassword({ newPw: E_npw, oldPw: encodePW }).then(res => {
      console.log('重置密码密码成功')
    })
  },

  saveToken({ commit, dispatch }, tokens = {}) {
    const { accessToken, refreshToken, tokenType, expiresIn } = tokens
    // console.log({ accessToken, refreshToken, tokenType, expiresIn })

    timer = expiresIn * 1000 // 前端秒需要*1000
    dispatch('updateToken')
    commit('SET_TOKEN', `${tokenType} ${accessToken}`)
    commit('SET_REFRESHTOKEN', refreshToken)
  },

  saveInfo({ commit }, info) {
    const { roleIds } = info
    if (1 || !info.avatar) {
      info.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    }
    commit('SET_ROLES', roleIds)
    commit('SET_USERINFO', info)
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        commit('SET_ROLES', ['admin'])
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ dispatch, state }) {
    return new Promise((resolve) => {
      dispatch('resetToken')
      resolve()
      state.userInfo.userId && logout(state.userInfo.userId)
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  /**
   * @description: 刷新token
   * @param {type}
   * @return {type}
   */
  updateToken({ dispatch }) {
    if (timeFn) {
      clearTimeout(timeFn)
      timeFn = null
    }
    timeFn = setTimeout(() => {
      dispatch('resetInfo')
    }, timer / 2)
  },
  resetInfo({ dispatch, state }) {
    return new Promise((resolve, reject) => {
      const grantType = 'refresh_token'
      const { tenantCode, refreshToken } = state
      login({ grantType, refreshToken, tenantCode }).then(response => {
        const { data: { user, ...tokens } = {}, code } = response
        if (code === 200) {
          dispatch('saveToken', tokens)
          dispatch('saveInfo', user)
          resolve()
        } else {
          reject()
        }
      }).catch(() => {
        reject()
      })
    })
  },
  getCaptcha({ commit }) {
    getCaptcha().then(res => {
      const { data, code } = res
      if (code === 200) {
        commit('SET_CAPTCHA', data)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

